<template>
  <div class="rightList">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加角色按钮 -->
    <el-button type="success" @click="addRoleDialogFormVisible=true">添加角色</el-button>
    <!-- 添加角色的dialog -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogFormVisible" >
      <el-form :model="addRoleForm" ref="addRoleForm">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="addRoleForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="addrole">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色表格 -->
    <el-table :data="rightList" style="width: 100%">
      <!-- 展开行 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            style="margin-bottom:15px;border-bottom:1px dashed #f00;"
            v-for="first in scope.row.children"
            :key="first.id"
          >
            <el-col :span="4">
              <el-tag closable @close="cnt=0;delRight(scope.row,first.id)">{{first.authName}}</el-tag>
            </el-col>
            <el-col :span="20">
              <el-row v-for="second in first.children" :key="second.id">
                <el-col :span="8">
                  <el-tag closable @close="cnt=0;delRight(scope.row,second.id)">{{second.authName}}</el-tag>
                </el-col>
                <el-col :span="16">
                  <el-tag
                    closable
                    style="margin-bottom:5px;margin-right:5px"
                    v-for="third in second.children"
                    :key="third.id"
                    @close="cnt=0;delRight(scope.row,third.id)"
                  >{{third.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-col :span="24" v-show="scope.row.children.length === 0">还没有任何的权限，先分配！！</el-col>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="180"></el-table-column>
      <el-table-column prop="roleDesc" label="描述" width="180"></el-table-column>
      <el-table-column prop="roleName" label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <el-button type="primary" icon="el-icon-edit"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="角色授权" placement="top">
            <el-button type="primary" icon="el-icon-share" @click="addSoleRight(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button type="primary" icon="el-icon-delete"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 角色授权树状对话框 -->
    <el-dialog title="角色授权" :visible.sync="rightDialogTableVisibles">
      <el-tree
      ref="tree"
        :data="allRihtList"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="checkArr"
        :props="defaultProps"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rightDialogTableVisibles = false">取 消</el-button>
        <el-button type="primary" @click="addRight">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 映入封装好的axios请求
import { getAllRole, delRoleRight, addRightById, addRole } from '@/api/role-index.js'
import { getAllRight } from '@/api/right-index.js'
export default {
  data () {
    return {
      roleId: '',
      cnt: 0,
      rightDialogTableVisibles: false,
      defaultProps: {
        label: 'authName',
        children: 'children'
      },
      // 选中节点的数组
      checkArr: [],
      // 角色所有权限
      allRihtList: [],
      // 表格的数据
      rightList: [],
      // 添加角色按钮dialog的数据
      addRoleDialogFormVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      formLabelWidth: '120px'
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    // 添加角色
    async addrole () {
      let res = await addRole(this.addRoleForm)
      // console.log(res)
      if (res.data.meta.status === 201) {
        this.$message.success(res.data.meta.msg)
        // 重置添加角色表单数据
        this.$refs.addRoleForm.resetFields()
        this.addRoleDialogFormVisible = false
        this.init()
      } else {
        this.$message.error(res.data.meta.msg)
      }
    },
    // 实现角色授权
    async addRight () {
      // 先获取到当前用户所选择所有的权限id,拼接 为以,分隔的字符串
      // console.log(this.$refs.tree.getCheckedNodes())
      let arr = this.$refs.tree.getCheckedNodes()
      // 2.遍历数组，进行数据的拼接
      let temp = []
      for (let i = 0; i < arr.length; i++) {
        temp.push(arr[i].id + ',' + arr[i].pid)
      }
      // console.log(temp)
      // 3.拼接数组元素再转换为数组
      temp = temp.join(',').split(',')
      // 4.数组才能去重  new Set(数组)可以去除数组中的重复数据，它的返回值是一个Set对象
      temp = [...new Set(temp)]
      // console.log(temp)
      // console.log(temp.join(','))
      // console.log(this.roleId)
      let res = await addRightById(this.roleId, temp.join(','))
      // console.log(res)
      if (res.data.meta.status === 200) {
        this.$message.success(res.data.meta.msg)
        this.rightDialogTableVisibles = false
        this.init()
      } else {
        this.$message.error(res.data.meta.msg)
      }
    },
    // 角色授权dialog对话框中权限选中
    addSoleRight (row) {
      // 这里进行数据的存储是为了后期角色授权时能够正确的获取角色id
      this.roleId = row.id
      this.rightDialogTableVisibles = true
      // 刷新用户角色权限树状
      getAllRight('tree').then(res => {
        console.log(res)
        this.allRihtList = res.data.data
      })
      // 清空选中节点数组
      this.checkArr.length = 0
      row.children.forEach(first => {
        if (first.children.length > 0) {
          first.children.forEach(second => {
            if (second.children.length > 0) {
              second.children.forEach(third => {
                this.checkArr.push(third.id)
              })
            }
          })
        }
      })
    },
    delRight (row, rightId) {
      // console.log(row.id, rightId)
      delRoleRight(row.id, rightId)
        .then(res => {
          if (this.cnt === 0) {
            this.$message.success(res.data.meta.msg)
            this.cnt++
          }
          row.children = res.data.data // 历遍一级权限
          row.children.forEach((v1, in1) => {
            if (v1.children.length === 0) {
              // 说明这个一级权限下面没有任何二级权限
              this.delRight(row, v1.id)
            } else {
              v1.children.forEach((v2, in2) => {
                if (v2.children.length === 0) {
                  // 说明这个二级权限下面没有任何三级权限
                  this.delRight(row, v2.id)
                }
              })
            }
          })
        })
        .catch(() => {
          this.$message.success('删除权限成功')
        })
    },
    init () {
      //   获取所有用户角色
      getAllRole()
        .then(res => {
          // console.log(res)
          this.rightList = res.data.data
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>

<style lang="less">
</style>
